package legumes.client.ui.widgets.window;

import java.util.Date;

import legumes.client.resources.PNResources;
import legumes.client.services.callbacks.SaveStoreCallback;
import legumes.client.services.util.rpc.RPCCallSequencer;
import legumes.client.ui.widgets.form.PostalAdressDynamicForm;
import legumes.client.ui.widgets.form.item.PlaceDeliveryFormItem;
import legumes.shared.domain.CivilityEnum;
import legumes.shared.domain.HomePlaceDelivery;
import legumes.shared.domain.LatLng;
import legumes.shared.domain.PlaceDelivery;
import legumes.shared.domain.PostalAdress;
import legumes.shared.domain.Store;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.events.CloseClientEvent;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.ButtonItem;
import com.smartgwt.client.widgets.form.fields.events.ClickEvent;
import com.smartgwt.client.widgets.form.fields.events.ClickHandler;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class StoreNewPlaceDeliveryEditionWindow extends Window {

	private Store store;
	
	private PlaceDelivery placeDelivery;
	private PlaceDeliveryFormItem placeDeliveryFi;
	private DynamicForm dfPlaceDeliveryFi;
	
	private PostalAdressDynamicForm postalAdressDynamicForm;
	
	private ButtonItem biValidate;
	private ButtonItem biCancel;
	
	private MapConfirmationOfPostalAdressWindow mapConfirmWnd;
	
	private PlaceDelivery placeDeliveryToEdit;
	private String [] placesAlreadyCreated;
	
	public StoreNewPlaceDeliveryEditionWindow(Store store_, String [] placesAlreadyCreated_) {
		this(store_, placesAlreadyCreated_, null);
	}

	public StoreNewPlaceDeliveryEditionWindow(Store store_,
			String [] placesAlreadyCreated_,
			PlaceDelivery placeDeliveryToEdit_) {
		super();
		store = store_;
		placesAlreadyCreated = placesAlreadyCreated_;
		placeDeliveryToEdit = placeDeliveryToEdit_;
		setTitle("<img src=\"" + PNResources.INSTANCE.deliveryIcon().getURL() + "\" />&nbsp;Cr&eacute;&eacute;r une nouvelle adresse");
		
		int windowHeight = com.google.gwt.user.client.Window.getClientHeight();
		if(windowHeight>=580 ){
			setHeight( 580 );
		} else {
			setHeight( 480 );
		}
		setWidth(640);
		setShowCloseButton(true);
		setShowMinimizeButton(false);
		setAutoCenter(true);
		setIsModal(true);
		setShowModalMask(true);
		addCloseClickHandler(new CloseClickHandler() {  
            public void onCloseClick(CloseClientEvent event) {  
            	StoreNewPlaceDeliveryEditionWindow.this.destroy();  
            }  
        });

		addItem( buildPanel() );
		show();
		placeDeliveryFi.focusInItem();
	}

	private VLayout buildPanel() {
		
		VLayout mainPanel = new VLayout();
		mainPanel.setWidth100();
		mainPanel.setHeight100();
		mainPanel.setMargin(10);
		
		Label lab = new Label(
				"<h3>Créer une nouvelle adresse de livraison</h3><BR />" +
				"INFO : Après validation, vous pourrez préciser à l'étape suivante si vous souhaiter effectuer des livraisons à domicile.");
		lab.setAutoHeight();
		
		placeDeliveryFi = new PlaceDeliveryFormItem(placesAlreadyCreated);
		if(placeDeliveryToEdit!=null){
			String [] othersPac = new String[placesAlreadyCreated.length-1];
			int i=0;
			placeDeliveryFi.setValue(placeDeliveryToEdit.getTitle());
			for(String pac : placesAlreadyCreated){
				if(!pac.equalsIgnoreCase(placeDeliveryToEdit.getTitle())){
					othersPac[i++]=pac;
				}
			}
			placeDeliveryFi.setPlacesAlreadyCreated(othersPac);
		}
		dfPlaceDeliveryFi =  new DynamicForm();
		dfPlaceDeliveryFi.setItems(placeDeliveryFi);
		
		postalAdressDynamicForm = new PostalAdressDynamicForm(
				placeDeliveryToEdit!=null?placeDeliveryToEdit.getPostalAdress():null );
		
		mainPanel.setMembers(lab, dfPlaceDeliveryFi, postalAdressDynamicForm, createButtons());
		
		return mainPanel;
	}

	private HLayout createButtons() {
		HLayout hlPanel = new HLayout();
		hlPanel.setWidth100();
		hlPanel.setHeight100();
		hlPanel.setMargin(10);
		
    	biValidate = new ButtonItem("AddToBasket", "Valider");
    	biValidate.setAutoFit(true);
    	biValidate.setColSpan(1);
    	biValidate.setAlign(Alignment.CENTER);
    	biValidate.setStartRow(false);
    	biValidate.setEndRow(false);
    	biValidate.setIcon( PNResources.INSTANCE.addIcon().getURL() );
    	biValidate.addClickHandler( new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				onBiValidateClicked();
			}
		} );
    	
    	biCancel = new ButtonItem("RemoveFromBasket", "Annuler");
    	biCancel.setIcon( PNResources.INSTANCE.cancelIcon().getURL() );
    	biCancel.setAlign(Alignment.CENTER);
    	biCancel.setStartRow(false);
    	biCancel.setEndRow(false);
    	biCancel.addClickHandler( new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				StoreNewPlaceDeliveryEditionWindow.this.destroy();
			}
		});
    	
    	DynamicForm df = new DynamicForm();
    	df.setNumCols(4);
    	df.setItems(biCancel, biValidate);
    	hlPanel.setMembers(df);
		return hlPanel;
	}

	private void onBiValidateClicked() {
		boolean isValidated = postalAdressDynamicForm.validate();
		isValidated &= dfPlaceDeliveryFi.validate();
		if( isValidated ){
			if(mapConfirmWnd==null){
				//We position the address on a map in order to validate the real lat lng position
				mapConfirmWnd = new MapConfirmationOfPostalAdressWindow(
						getPostalAdress(),
						getWidth(),
						getHeight(),
						placeDeliveryToEdit
				){
	
					@Override
					void onValidateAction(boolean isDeliveringAtHome_, int homeDeliveringAreaRadius_) {
						mapConfirmWnd.showLoading();
						onConfirmAdress(mapConfirmWnd.getLatLng(), isDeliveringAtHome_, homeDeliveringAreaRadius_);
					}
				};
			} else {
				mapConfirmWnd.show();
			}
		}
	}
	
	private void onConfirmAdress(LatLng latLngConfirm_,boolean isDeliveringAtHome_,int homeDeliveringAreaRadius_){
		PlaceDelivery modifiedPlaceDelivery;
//		if(placeDeliveryToEdit != null){
//			placeDeliveryToEdit.setTitle( placeDeliveryFi.getValueAsString() );
//			placeDeliveryToEdit.setPostalAddress(getPostalAdress());
//			placeDeliveryToEdit.setLatLng(latLngConfirm_);
//			modifiedPlaceDelivery = placeDeliveryToEdit;
//			store.updatePlaceDelivery(placeDeliveryToEdit);
//		} else {
			if(isDeliveringAtHome_){
				placeDelivery = new HomePlaceDelivery();
				((HomePlaceDelivery)placeDelivery).setRadiusKm(homeDeliveringAreaRadius_);
			} else {
				placeDelivery = new PlaceDelivery();
			}
			
			placeDelivery.setId(new Date().getTime());
			placeDelivery.setTitle( placeDeliveryFi.getValueAsString() );
			placeDelivery.setPostalAddress(getPostalAdress());
			placeDelivery.setLatLng(latLngConfirm_);
			modifiedPlaceDelivery = placeDelivery;
//			store.addPlaceDelivery(placeDelivery);
			store.updatePlaceDelivery(placeDeliveryToEdit, placeDelivery);
			if(placeDeliveryToEdit != null){
				placeDeliveryToEdit = placeDelivery;
			}
//		}
		
		saveOnServer(modifiedPlaceDelivery);
	}
	
	private void saveOnServer(final PlaceDelivery modifiedPlaceDelivery_){
		RPCCallSequencer callSequencer = new RPCCallSequencer("Enregistrement en cours...");
		final SaveStoreCallback saveStoreCallback = new SaveStoreCallback(
				store);
		callSequencer.addCall(saveStoreCallback);
		callSequencer.addRunnable(new Runnable() {
			public void run() {
				mapConfirmWnd.hideLoading();
				mapConfirmWnd.destroy();
				onStoreSaved(store, modifiedPlaceDelivery_);
				StoreNewPlaceDeliveryEditionWindow.this.destroy();
			}
		});
		callSequencer.callSequence();
	}
	
	protected void onStoreSaved(Store store_, PlaceDelivery modifiedPlaceDelivery_){
		
	}
	
	public PostalAdress getPostalAdress(){
		PostalAdress pAdress = new PostalAdress();
		pAdress.setId(new Date().getTime());
		pAdress.setAdressPrecision(getAdressPrecision());
		pAdress.setBuilding(getBuilding());
		pAdress.setCivility(getCivilityEnum().name());
		pAdress.setCompanyName(getCompanyName());
		pAdress.setCountry(getCountry());
		pAdress.setFirstName(getFirstName());
		pAdress.setFlat(getFlat());
		pAdress.setLastName(getLastName());
		pAdress.setPhone1(getPhoneFixe());
		pAdress.setPhone2(getPhonePortable());
		pAdress.setPlaceCalled(getPlaceCalled());
		pAdress.setStreet(getStreet());
		pAdress.setTown(getTown());
		pAdress.setZipCode(getZipCode());
		
		return pAdress;
	}
	

	private CivilityEnum getCivilityEnum(){
		return postalAdressDynamicForm.getCivilityEnum();
	}
	
	private String getLastName(){
		return postalAdressDynamicForm.getLastName();
	}
	
	private String getFirstName(){
		return postalAdressDynamicForm.getFirstName();
	}
	
	private String getCompanyName(){
		return postalAdressDynamicForm.getCompanyName();
	}
	
	private String getFlat(){
		return postalAdressDynamicForm.getFlat();
	}
	
	private String getBuilding(){
		return postalAdressDynamicForm.getBuilding();
	}
	
	private String getStreet(){
		return postalAdressDynamicForm.getStreet();
	}
	
	private String getPlaceCalled(){
		return postalAdressDynamicForm.getPlaceCalled();
	}
	
	private String getZipCode(){
		return postalAdressDynamicForm.getZipCode();
	}
	
	private String getTown(){
		return postalAdressDynamicForm.getTown();
	}
	
	private String getCountry(){
		return postalAdressDynamicForm.getCountry();
	}
	
	private String getPhoneFixe(){
		return postalAdressDynamicForm.getPhoneFixe();
	}
	
	private String getPhonePortable(){
		return postalAdressDynamicForm.getPhonePortable();
	}
	
	private String getAdressPrecision(){
		return postalAdressDynamicForm.getAdressPrecision();
	}

}
